package Control;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.ConnectDatabase;
import Model.MD5Hash;
import Model.Quyen;
import Model.User;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ControlRegister
 */
public class ControlRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int ERROR_NUM = 11;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ControlRegister() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		 response.setContentType("text/html;charset=UTF-8");
	        request.setCharacterEncoding("UTF-8");
	        response.setCharacterEncoding("UTF-8");

	        boolean check[] = new boolean[ERROR_NUM];
	        for (int i = 0; i < check.length; i++) {
	            check[i] = true;
	        }
	        String username = request.getParameter("username");
	        String password = request.getParameter("password");
	        String name = request.getParameter("name");
	        String address = request.getParameter("address");
	        String province = request.getParameter("province");
	        String phone = request.getParameter("phone");
	        String email = request.getParameter("email");
	        String captcha = request.getParameter("captcha");
//	        if ((username.length() < 4) || (username.length() > 10)) {
//	            request.setAttribute("username_error", "Username  Phải Lớn Hơn 4 Ký Tự Và Nhỏ hơn 10 Ký Tự !");
//	            check[1] = false;
//	        }
//	        if ((password.length() < 6)) {
//	            request.setAttribute("password_error", "Password Phải Lớn Hơn 6 Ký Tự Và Nhỏ hơn 8 Ký Tự !");
//	            check[2] = false;
//	        }

	        if (name.length() < 8) {
	            request.setAttribute("name_error", "Họ Và Tên  Phải Có 8 Hơn Ký Tự !");
	            check[4] = false;
	        }
	        if (address.length() < 7) {
	            request.setAttribute("address_error", " Địa Chỉ  Phải Có 7 Hơn Ký Tự !");
	            check[5] = false;
	        }
	        if(!captcha.equals(request.getSession().getAttribute("CorrectAnswer"))){
	            request.setAttribute("captcha_error", "Bạn Nhập sai mã captcha");
	            check[10] = false; 
	        }
	        for (int i = 0; i < check.length; i++) {
	            if (check[i] == false) {
	                RequestDispatcher dispatcherObject = getServletContext().getRequestDispatcher("/index.jsp?register");
	                dispatcherObject.forward(request, response);
	                System.err.println("Error page");
	            }
	        }




	        if (checkUserName(username) == true) {
	            response.sendRedirect("index.jsp?register&error_username=error username");
	            return;
	        }
	        if (checkEmail(email) == true) {
	            response.sendRedirect("index.jsp?register&error_email=error email");
	            return;
	        }

	        User user = new User(username, password, name, address, province, phone, email, new Quyen(1));
	        user.Save(user);
	        
	        HttpSession session = request.getSession();
	        session.setAttribute("sessionlogin", user);
	        
	        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/userregisterinfo.jsp");
	        dispatcher.forward(request, response);






	    }

	    private boolean checkUserName(String username) {
	        boolean kq = false;
	        Connection con = ConnectDatabase.getConnection();
	        try {
	            Statement state = con.createStatement();
	            String sql = "select * from user";
	            ResultSet result = state.executeQuery(sql);
	            while (result.next()) {
	                String checkUser = result.getString(2);
	                if (checkUser.equals(username)) {
	                    kq = true;
	                    break;
	                }
	            }
	            con.close();
	        } catch (SQLException ex) {
	            ex.printStackTrace();
	        }
	        System.out.println(kq);
	        return kq;
	    }

	    private boolean checkEmail(String email) {
	        boolean kq = false;
	        Connection con = ConnectDatabase.getConnection();
	        try {
	            Statement state = con.createStatement();
	            String sql = "select * from user ";
	            ResultSet result = state.executeQuery(sql);
	            while (result.next()) {
	                String em = result.getString(8);
	                if (em.equals(email)) {
	                    kq = true;
	                    break;
	                }
	            }
	            con.close();
	        } catch (SQLException ex) {
	            ex.printStackTrace();
	        }


	        return kq;
	    }
		
		
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
